package com.yyx.jupiter.service.recommend.rank;

import com.alibaba.fastjson2.JSONObject;
import com.yyx.jupiter.conf.PropertyConfig;
import com.yyx.jupiter.entity.RecomReq;
import com.yyx.jupiter.entity.RecomVideo;
import com.yyx.jupiter.component.RedisClient;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class HobbyRank implements Rankable<RecomVideo> {

    @Resource
    PropertyConfig propertyConfig;

    @Resource
    RedisClient redisClient;

    @Override
    public List<RecomVideo> rank(List<RecomVideo> recomItems, RecomReq recomReq) throws Exception {
        long startTime = System.currentTimeMillis();

        // 请求体参数
        String userId = recomReq.getUserId();
        String strategy = recomReq.getStrategy();
        boolean isPreferRecommend = recomReq.getIsPreferRecommend();

        // 配置参数
        JSONObject strategyJson = propertyConfig.getStrategy().getJSONObject(strategy);
        boolean logPrintSwitch = MapUtils.getBooleanValue(strategyJson, "logPrintSwitch", false);

        // 获取用户喜好
        String hobbies = redisClient.get(userId, String.class);

        // 获取用户喜好视频
        if (isPreferRecommend && hobbies != null) {
            recomItems = recomItems.stream().filter(t -> hobbies.contains(t.getSecondCategory())).toList();
        }

        // 按时间排序
        recomItems = recomItems.stream().sorted(Comparator.comparing(RecomVideo::getCreateTime).reversed()).toList();

        if (logPrintSwitch) {
            log.info("requestId:{}, hobby rank process elapsed: {} ms, rank size: {}",
                    recomReq.getRequestId(), (System.currentTimeMillis() - startTime), recomItems.size());
        }

        return recomItems;
    }
}
